package com.util;

import java.io.InputStream;
import java.io.OutputStream;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Enumeration;

import org.springframework.stereotype.Component;

import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.NoSuchPortException;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;


/**
 *  ==>串口管理
 */
@Component
public class SerialPortManager {

	public static SerialPort openPort=null;//正在使用的串口对象
	public static String nowPort=null; //正在使用的串口参数：端口号
	public static byte[] readData=null; 
	/**
     * ==> 查找所有可用端口
     * @return 可用端口名称列表
     */
    public static final ArrayList<String> findPorts() {
        // 获得当前所有可用串口
        @SuppressWarnings("unchecked")
		Enumeration<CommPortIdentifier> portList = CommPortIdentifier.getPortIdentifiers();
        ArrayList<String> portNameList = new ArrayList<String>();
        // 将可用串口名添加到List并返回该List
        while (portList.hasMoreElements()) {
            String portName = portList.nextElement().getName();
            portNameList.add(portName);
        }
        return portNameList;
    }

    /**
     * ==> 打开串口
     *
     * @param portName 端口名称
     * @param baudrate 波特率
     * @return 串口对象
     * @throws PortInUseException 串口已被占用
     */
    public final SerialPort openPort(String portName, int baudrate) throws Exception {
            // 通过端口名识别端口
            CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
            // 打开端口，并给端口名字和一个timeout（打开操作的超时时间）
            CommPort commPort = portIdentifier.open(portName, 2000);
            // 判断是不是串口
            if (commPort instanceof SerialPort) {
                SerialPort serialPort = (SerialPort) commPort;
                try {
                    // 设置一下串口的波特率等参数
                    // 数据位：8
                    // 停止位：1
                    // 校验位：None
                    serialPort.setSerialPortParams(baudrate, SerialPort.DATABITS_8, SerialPort.STOPBITS_1,
                            SerialPort.PARITY_NONE);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return serialPort;
            }
   
        return null;
    }

    /**
     *  ==> 关闭串口
     * @param serialport 待关闭的串口对象           
     * @throws NoSuchPortException 
     */
    public  static  void closePort(){
        if (SerialPortManager.openPort != null) {
        	System.out.println("开始设置false");
        	SerialPortManager.openPort.notifyOnDataAvailable(false);
        	System.out.println("开始移除监听");
        	SerialPortManager.openPort.removeEventListener();
        	System.out.println("开始关闭");
        	SerialPortManager.openPort.close();
            System.out.println("关闭完成");
            SerialPortManager.openPort=null;
        }else {
        	System.out.println("端口已经为空");
        }
    }

    /**
     *  ==>往串口发送数据
     *
     * @param serialPort 串口对象        
     * @param order 待发送数据
     */
    @SuppressWarnings("deprecation")
	public static boolean sendToPort(SerialPort serialPort, byte[] postData) {
    	Thread thread=new Thread(()->{
    		OutputStream out = null;
	        try {
	            out = serialPort.getOutputStream();
	            out.write(postData);
	            out.flush();
	        } catch (Exception e) {
	            e.printStackTrace();
	        } finally {
	            try {
	                if (out != null) {
	                    out.close();
	                    out = null;
	                }
	            } catch (Exception e) {
	                e.printStackTrace();
	            }
	        }
    	});
    	thread.start();
    	LocalDateTime begin = LocalDateTime.now();
    	System.out.println("给设备发送数据中....");
    	while (thread.isAlive()) {
    		//等待数据读取
			LocalDateTime now = LocalDateTime.now();
			Duration duration = Duration.between(begin, now);
			long millis = duration.toMillis();
			if(millis>=5000) {//5秒断开
				System.out.println("5秒断开超时断开,数据未发送成功！");
				thread.stop();
				return false;
			}
		}
    	return true;
    }

    /**
     * ==> 从串口读取数据
     * @param serialPort 当前已建立连接的SerialPort对象
     * @return 读取到的数据
     */
    public static byte[] readFromPort(SerialPort serialPort) throws Exception {
        InputStream in = null;
        byte[] bytes = {};
        try {
        	 in = serialPort.getInputStream();
             byte[] buffer=new byte[1];
             in.read(buffer);
             String bufferString = FrameUtil.bytesToHexString(buffer);
             while(!bufferString.toLowerCase().equals("7e")) {
            	 in.read(buffer);
            	 bufferString = FrameUtil.bytesToHexString(buffer);
             }
             bytes = FrameUtil.addBytes(bytes, buffer);
             while(!bufferString.toLowerCase().equals("7f")) {
            	 in.read(buffer);
            	 bytes = FrameUtil.addBytes(bytes, buffer);
            	 bufferString = FrameUtil.bytesToHexString(buffer);
             }
        } catch (Exception  e) {
            throw new Exception("读取失败，关闭端口");
        } finally {
            try {
                if (in != null) {
                    in.close();
                    in = null;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return bytes;
    }

    /**
     * ==> 添加监听器
     * @param port 串口对象
     * @param listener  串口存在有效数据监听
     */
    public  void addListener(SerialPort serialPort, Result<String> result) {
        try {
            // 给串口添加监听器
        	System.out.println("给串口添加监听器");
            serialPort.addEventListener(new SerialPortListener(result,serialPort));
            // 设置当有数据到达时唤醒监听接收线程
            System.out.println("设置当有数据到达时唤醒监听接收线程");
            serialPort.notifyOnDataAvailable(true);
            // 设置当通信中断时唤醒中断线程
            System.out.println("设置当通信中断时唤醒中断线程");
            serialPort.notifyOnBreakInterrupt(true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * ==> 串口监听
     */
    public  class SerialPortListener implements SerialPortEventListener {

        private Result<String> result;
        private SerialPort serialPort;

        public SerialPortListener(Result<String> result,SerialPort serialPort) {
        	this.serialPort=serialPort;
            this.result = result;
        }

       
        public void serialEvent(SerialPortEvent serialPortEvent) {
            switch (serialPortEvent.getEventType()) {
                case SerialPortEvent.DATA_AVAILABLE: // 1.串口存在有效数据
                    if (serialPort != null) {
                    	byte[] data;
                        try {
                            // 读取串口数据
                            data = SerialPortManager.readFromPort(serialPort);
                            String all = FrameUtil.bytesToHexString(data);
                            System.out.println("设备返回原始参数："+all);
                            String replaceAll = all.replaceAll("7D01", "7E").replaceAll("7D02", "7F").replaceAll("7D03","7D"); //转义
                            data=FrameUtil.hexToByteArray(replaceAll);
                            result.setData(replaceAll);
                            readData=data;
                        } catch (Exception e) {
                            SerialPortManager.closePort();
                            result.setCode(500);
                            result.setMsg(e.getMessage());
                            serialPort=null;
                            e.printStackTrace();
                        }
                        
                    }
                    break;

                case SerialPortEvent.OUTPUT_BUFFER_EMPTY: // 2.输出缓冲区已清空
                    break;

                case SerialPortEvent.CTS: // 3.清除待发送数据
                    break;

                case SerialPortEvent.DSR: // 4.待发送数据准备好了
                    break;

                case SerialPortEvent.RI: // 5.振铃指示
                    break;

                case SerialPortEvent.CD: // 6.载波检测
                    break;

                case SerialPortEvent.OE: // 7.溢位（溢出）错误
                    break;

                case SerialPortEvent.PE: // 8.奇偶校验错误
                    break;

                case SerialPortEvent.FE: // 9.帧错误
                    break;

                case SerialPortEvent.BI: // 10.通讯中断
                    System.out.println("======与串口设备通讯中断");
                    break;

                default:
                    break;
            }
        }
    }

}
